package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.myapplication1.Adapter.MsgAdapter;
import com.example.myapplication1.Bean.Msg;

import org.litepal.LitePal;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Main2Activity extends AppCompatActivity {
    TextView chattxt;
Button sendbtn;
EditText sendedit;
ListView chatlv;
int sendid,receiveid;

String receivname;
List<Msg>msgList=new ArrayList<>();
   // List<String>dataList=new ArrayList<>();
    MsgAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initData();
        ininView();
        setListener();
    }

    private void initData() {
        //取出数据
        SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
        sendid=sp.getInt("myid",-1);
        receiveid=sp.getInt("friendid",-1);
        receivname=sp.getString("friendname","");
        for (Msg m:LitePal.findAll(Msg.class)){//循环
            Log.e("msg",m.getSend_id()+" "+m.getReceive_id()+" "+m.getContent());
            boolean a= sendid==m.getSend_id()&&receiveid==m.getReceive_id();//我发送
            boolean b= sendid==m.getReceive_id()&&receiveid==m.getSend_id();//对方发送
            if (a||b){
                msgList.add(m);
            }
        }

        }
    //点击监听事件
    private void setListener() {
        sendbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content=sendedit.getText().toString().trim();
                Msg m=new Msg(0,sendid,receiveid,content,new Date());
                m.save();
                msgList.add(m);
               // dataList.add(m.getContent());
                adapter.notifyDataSetChanged();

            }
        });
    }

    private void ininView() {
        sendbtn=findViewById(R.id.sendbtn);
        sendedit=findViewById(R.id.sendedit);
        chatlv=findViewById(R.id.chatlv);
        chattxt=findViewById(R.id.chattxt);
        chattxt.setText("正在与"+receivname+"聊天中");
        adapter=new MsgAdapter(Main2Activity.this,
                R.layout.msg_item,msgList);
        chatlv.setAdapter(adapter);

    }
}
